package org.example.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Value("${hjh.uploadDir}")
    private String baseImagePath;

    /**
     * 配置静态资源访问
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (baseImagePath.charAt(baseImagePath.length() - 1) != '/' && baseImagePath.charAt(baseImagePath.length() - 1) != '\\'){
            baseImagePath = baseImagePath + "/";
        }
        registry.addResourceHandler("/upload/**")
                .addResourceLocations("file:"+baseImagePath);
    }

    /**
     * 配置跨域访问
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("GET","POST","HEAD","DELETE","PUT","OPTION")
                .allowedOrigins("*")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600); // 5s
    }
}
